//
//  KKImagePickerModel.m
//  KKImagePickerController
//
//  Created by Leo on 15/6/25.
//  Copyright (c) 2015年 Juvid. All rights reserved.
//

#import "KKImagePickerModel.h"
#import "KKAlertView.h"
@interface KKImagePickerModel() {
    
    NSMutableArray* _itemArray;
}

@end

@implementation KKImagePickerModel

static KKImagePickerModel* pickerModel = nil;
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pickerModel = [KKImagePickerModel new];
    });
    return pickerModel;
}

- (id)init {
    self = [super init];
    if (self) {
        _itemArray = [NSMutableArray array];
    }
    return self;
}

- (void)addItemToArray:(ALAsset*)assetItem {
    
    if (assetItem == nil) {
        return;
    }
    
    if (_maxCount != 0 && _itemArray.count == _maxCount) {
        
//        [[KKResultAlertView sharedInstance] alertViewShowMessage: [NSString stringWithFormat: @"已经选中了%@张", @(_maxCount)] andWithSuccessful: false andWithCallBack: nil];
       
        return;
    }
    
    [_itemArray addObject: assetItem];
    
    [self setCount: _itemArray.count];
}

- (ALAsset*)itemOfIndex:(NSInteger)index {
    
    if (index < _itemArray.count) {
        return _itemArray[index];
    }
    return nil;
}

- (void)removeItemFromArray:(ALAsset*)assetItem {
    
    if ([self matchItem: assetItem]) {
        [_itemArray removeObject: assetItem];
        
        [self setCount: _itemArray.count];
    }
}

- (BOOL)matchItem:(ALAsset*)assetItem {
    
    for (ALAsset* item in _itemArray) {
        
        NSString* itemURL = [NSString stringWithFormat: @"%@", [item valueForProperty: ALAssetPropertyAssetURL]];
        NSString* assetURL = [NSString stringWithFormat: @"%@", [assetItem valueForProperty: ALAssetPropertyAssetURL]];
        
        if ([itemURL isEqualToString: assetURL]) {
            return YES;
        }
    }
    
    return NO;
}

- (void)cleanAllItems {
    
    [_itemArray removeAllObjects];
    [self setCount: _itemArray.count];
}

- (NSArray*)allItems {
    
    return [NSArray arrayWithArray: _itemArray];
}

@end
